import React, { useState, useEffect } from 'react';
import { useNavigate, Link, useLocation } from 'react-router-dom';
import { 
  Button, 
  Space, 
  Avatar,
  Dropdown,
  Layout,
  Tooltip,
  message,
  Modal,
  Select,
  Form
} from 'antd';
import { 
  HomeOutlined, 
  LeftOutlined, 
  RightOutlined, 
  RetweetOutlined,
  PlayCircleOutlined,
  SendOutlined,
  UserOutlined,
  CodeOutlined,
  LogoutOutlined,
  BookOutlined,
  PlusOutlined
} from '@ant-design/icons';
import styles from './ProblemHeader.module.css';
import ProblemList from './ProblemList';
import { accountService } from '@/services/accountService';
import { User } from '@/types/account';
import { problemService } from '@/services/problemService';
import { Problem } from '@/types/problem';
import { problemSetService } from '@/services/problemSetService';
import { ProblemSet } from '@/types/problemSet';
import http from '@/http';

const { Header } = Layout;

interface ProblemHeaderProps {
  id?: string;
  problem?: Problem; // 添加题目完整信息
  isAuthenticated: boolean;
  user: User | null;
  submitting: boolean;
  onTest: () => void;
  onSubmit: () => void;
  onLogout: () => void;
}

const ProblemHeader: React.FC<ProblemHeaderProps> = ({
  id,
  problem,
  isAuthenticated,
  user,
  submitting,
  onTest,
  onSubmit,
  onLogout
}) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [problemListVisible, setProblemListVisible] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState<string>('');
  const [contestProblems, setContestProblems] = useState<Problem[]>([]);
  const [currentProblemIndex, setCurrentProblemIndex] = useState<number>(-1);
  
  // 添加题目到题单相关状态
  const [addToSetModalVisible, setAddToSetModalVisible] = useState(false);
  const [problemSets, setProblemSets] = useState<ProblemSet[]>([]);
  const [loadingProblemSets, setLoadingProblemSets] = useState(false);
  const [addingToSet, setAddingToSet] = useState(false);
  const [form] = Form.useForm();
  
  // 从URL中提取contest_id、origin和problemSetId参数
  const urlParams = new URLSearchParams(location.search);
  const contestId = urlParams.get('contest_id');
  const origin = urlParams.get('origin'); // 新增：获取origin参数
  const problemSetId = urlParams.get('problemSetId'); // 新增：获取题单ID参数
  
  // 如果有比赛ID和题目ID，获取比赛题目列表并确定当前题目的位置
  useEffect(() => {
    if (contestId && id) {
      fetchContestProblems();
    }
  }, [contestId, id]);
  
  // 获取比赛题目列表
  const fetchContestProblems = async () => {
    try {
      const response = await problemService.getProblems({ contest_id: Number(contestId) });
      if (response.data) {
        const problemData = 'data' in response.data ? response.data.data : response.data;
        const problemList = problemData.results || [];
        
        // 确保题目列表是有效的
        const validProblems = problemList.filter(p => p && typeof p === 'object' && p.id);
        setContestProblems(validProblems);
        
        // 找到当前题目在列表中的索引位置
        const index = validProblems.findIndex(p => p.id === Number(id));
        setCurrentProblemIndex(index);
      }
    } catch (error) {
      console.error('获取比赛题目列表失败:', error);
    }
  };
  
  // 处理上一题按钮点击事件
  const handlePrevProblem = () => {
    if (contestId && currentProblemIndex > 0) {
      const prevProblem = contestProblems[currentProblemIndex - 1];
      // 保持origin参数
      const params = new URLSearchParams();
      if (contestId) params.set('contest_id', contestId);
      if (origin) params.set('origin', origin);
      if (problemSetId) params.set('problemSetId', problemSetId);
      navigate(`/problem/${prevProblem.id}/submit?${params.toString()}`);
    } else if (contestId && currentProblemIndex === 0) {
      // 如果已经是第一题，显示提示
      message.info('已经是第一题了，没有更多题目了');
    }
  };
  
  // 处理下一题按钮点击事件
  const handleNextProblem = () => {
    if (contestId && currentProblemIndex >= 0 && currentProblemIndex < contestProblems.length - 1) {
      const nextProblem = contestProblems[currentProblemIndex + 1];
      // 保持origin参数
      const params = new URLSearchParams();
      if (contestId) params.set('contest_id', contestId);
      if (origin) params.set('origin', origin);
      if (problemSetId) params.set('problemSetId', problemSetId);
      navigate(`/problem/${nextProblem.id}/submit?${params.toString()}`);
    } else if (contestId && currentProblemIndex === contestProblems.length - 1) {
      // 如果已经是最后一题，显示提示
      message.info('已经是最后一题了，没有更多题目了');
    }
  };
  
  // 上一题按钮是否禁用
  const isPrevButtonDisabled = () => {
    if (!contestId) return true; // 不是比赛，禁用
    return false; // 允许点击，即使是第一题也可以点击（用于显示提示）
  };
  
  // 下一题按钮是否禁用
  const isNextButtonDisabled = () => {
    if (!contestId) return true; // 不是比赛，禁用
    return false; // 允许点击，即使是最后一题也可以点击（用于显示提示）
  };

  useEffect(() => {
    // 如果用户已登录且有头像，使用getAvatarUrl获取完整URL
    if (isAuthenticated && user?.avatar) {
      setAvatarUrl(http.getAvatarUrl(user.avatar));
    } else {
      setAvatarUrl('');
    }
  }, [isAuthenticated, user]);

  // 获取用户头像 - 参考UserLayout的实现
  useEffect(() => {
    if (isAuthenticated && user) {
      const fetchAvatar = async () => {
        try {
          const response = await accountService.getProfile();
          if (response.data && response.data.avatar) {
            setAvatarUrl(http.getAvatarUrl(response.data.avatar));
          }
        } catch (error) {
          console.error('获取用户头像失败:', error);
        }
      };
      
      fetchAvatar();
    }
  }, [isAuthenticated, user]);

  // 随机跳转到一个题目
  const goToRandomProblem = () => {
    const randomId = Math.floor(Math.random() * 100) + 1;
    // 保持origin参数
    const params = new URLSearchParams();
    if (origin) params.set('origin', origin);
    if (problemSetId) params.set('problemSetId', problemSetId);
    const queryString = params.toString();
    navigate(`/problem/${randomId}/submit${queryString ? `?${queryString}` : ''}`);
  };

  // 显示题库列表
  const showProblemList = () => {
    setProblemListVisible(true);
  };

  // 关闭题库列表
  const closeProblemList = () => {
    setProblemListVisible(false);
  };
  
  // 显示添加题目到题单的模态框
  const showAddToSetModal = async () => {
    // 检查管理员权限
    if (user?.admin_type === "Regular User") {
      message.error('只有管理员才能使用此功能');
      return;
    }
    
    setAddToSetModalVisible(true);
    await fetchProblemSets();
  };
  
  // 关闭添加题目到题单的模态框
  const closeAddToSetModal = () => {
    setAddToSetModalVisible(false);
    form.resetFields();
  };
  
  // 获取用户的题单列表
  const fetchProblemSets = async () => {
    try {
      setLoadingProblemSets(true);
      const response = await problemSetService.getProblemSets();
      if (response.data) {
        const data = 'data' in response.data ? response.data.data : response.data;
        setProblemSets(data.results || []);
      }
    } catch (error) {
      console.error('获取题单列表失败:', error);
      message.error('获取题单列表失败');
    } finally {
      setLoadingProblemSets(false);
    }
  };
  
  // 添加题目到题单
  const handleAddToSet = async (values: { problemSetId: number }) => {
    console.log('handleAddToSet called, problem:', problem);
    console.log('problem._id:', problem?._id);
    
    if (!problem?._id) {
      message.error('题目ID不存在');
      return;
    }
    
    try {
      setAddingToSet(true);
      await problemSetService.addProblemToSet(values.problemSetId, {
        problem_id: problem._id
      });
      message.success('题目已成功添加到题单');
      closeAddToSetModal();
    } catch (error: any) {
      console.error('添加题目到题单失败:', error);
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error('添加题目到题单失败');
      }
    } finally {
      setAddingToSet(false);
    }
  };
  
  // 用户菜单项
  const userMenuItems = [
    {
      key: 'profile',
      label: '个人中心',
      icon: <UserOutlined />,
      onClick: () => navigate('/profile')
    },
    {
      key: 'submissions',
      label: '我的提交',
      icon: <CodeOutlined />,
      onClick: () => navigate('/submissions')
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: onLogout
    }
  ];
  
  // 获取题库按钮文本
  const getProblemBankButtonText = () => {
    if (contestId) return '题目';
    if (origin === 'contest') return '比赛题目';
    if (origin === 'problemset') return '题单';
    return '题库';
  };

  return (
    <Header className={styles.header}>
      <div className={styles.leftSection}>
        <Button 
          type="text" 
          icon={<BookOutlined />} 
          onClick={showProblemList}
          className={styles.problemBankButton}
        >
          {getProblemBankButtonText()}
        </Button>
        
        <Space className={styles.navButtons}>
          {contestId ? (
            // 比赛模式：显示上一题和下一题按钮
            <>
              <Tooltip title="上一题">
                <Button 
                  type="text" 
                  icon={<LeftOutlined />} 
                  onClick={handlePrevProblem}
                  disabled={isPrevButtonDisabled()}
                  className={styles.navButton}
                />
              </Tooltip>
              
              <Tooltip title="下一题">
                <Button 
                  type="text" 
                  icon={<RightOutlined />} 
                  onClick={handleNextProblem}
                  disabled={isNextButtonDisabled()}
                  className={styles.navButton}
                />
              </Tooltip>
            </>
          ) : (
            // 非比赛模式：只显示随机一题按钮
            <Tooltip title="随机一题">
              <Button 
                type="text" 
                icon={<RetweetOutlined />} 
                onClick={goToRandomProblem}
                className={styles.navButton}
              />
            </Tooltip>
          )}
          
          {/* 添加题目到题单按钮 - 仅管理员可见 */}
          {user?.admin_type !== "Regular User" && (
            <Tooltip title="添加到题单">
              <Button 
                type="text" 
                icon={<PlusOutlined />} 
                onClick={showAddToSetModal}
                className={styles.navButton}
              />
            </Tooltip>
          )}
        </Space>
      </div>
      
      <div className={styles.centerActions}>
        <Space>
          <Button 
            type="primary" 
            icon={<PlayCircleOutlined />} 
            onClick={onTest}
            loading={submitting}
            className={`${styles.actionButton} ${styles.runButton}`}
          >
            运行
          </Button>
          
          <Button 
            type="primary" 
            icon={<SendOutlined />} 
            onClick={onSubmit}
            loading={submitting}
            className={`${styles.actionButton} ${styles.submitButton}`}
          >
            提交
          </Button>
        </Space>
      </div>
      
      <div className={styles.rightSection}>
        <Tooltip title="首页">
          <Button 
            type="text" 
            icon={<HomeOutlined />} 
            onClick={() => navigate('/')}
            className={styles.navButton}
          />
        </Tooltip>
        
        {isAuthenticated ? (
          <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
            <Space className={styles.userDropdown}>
              <Avatar 
                src={avatarUrl} 
                icon={<UserOutlined />} 
                className={styles.avatar}
              />
              <span className={styles.username}>{user?.username}</span>
            </Space>
          </Dropdown>
        ) : (
          <Button 
            type="link" 
            onClick={() => navigate('/login')}
          >
            登录
          </Button>
        )}
      </div>
      
      <ProblemList 
        visible={problemListVisible} 
        onClose={closeProblemList} 
        contest_id={contestId}
        origin={origin} // 新增：传递origin参数
        problemSetId={problemSetId} // 新增：传递题单ID参数
      />
      
      {/* 添加题目到题单的模态框 */}
      <Modal
        title="添加题目到题单"
        open={addToSetModalVisible}
        onCancel={closeAddToSetModal}
        footer={null}
        destroyOnClose
      >
        <Form
          form={form}
          onFinish={handleAddToSet}
          layout="vertical"
        >
          <Form.Item
            name="problemSetId"
            label="选择题单"
            rules={[{ required: true, message: '请选择题单' }]}
          >
            <Select
              placeholder="请选择题单"
              loading={loadingProblemSets}
              showSearch
              filterOption={(input, option) =>
                (option?.children as unknown as string)?.toLowerCase().includes(input.toLowerCase())
              }
            >
              {problemSets.map(problemSet => (
                <Select.Option key={problemSet.id} value={problemSet.id}>
                  {problemSet.title} ({problemSet.problem_count}题)
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={closeAddToSetModal}>
                取消
              </Button>
              <Button 
                type="primary" 
                htmlType="submit"
                loading={addingToSet}
              >
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </Header>
  );
};

export default ProblemHeader; 